<?php

/**
 * Generador de mantenimientos rapidos
 *
 * @author EaDeveloper
 */
class FastMaintenance extends Maintenance {

    public $gridmanager = null;
    public $fieldsConfig = array();
    public $pkFields = array();
    public $currentRecord = array();
    public $gridProperties = array();
    public $instanceName = "FastMaintenance";
    public $autoPK = false;
    public $encryptedCols = array();
    public $readOnlyCols = array();
    public $gridCols = array();
    public $fieldsToSkipOnUpdate = array();

    public function includeWidget() {
        
    }

    /**
     * Generador del formulario
     * @param type $ajax 
     */
    public function generaForma($ajax = false) {
        if (!$ajax) {
            ?>
            <div id="dialog-cargando" style="width: auto; height: auto; vertical-align: middle; text-align: center; display: none">
                <img alt="Cargando"  id="img-cargando" src='img/loading.gif' style="width: 100px; height: 100px" />
            </div>
            <form id="<?php echo $this->formName; ?>"
                  name="<?php echo $this->formName; ?>"
                  method="post" action="<?php echo CORE_PATH; ?>">
                <input type="hidden" id="module" name="module" value="<?php echo $this->instanceName; ?>" />
                <? foreach ($this->pkFields as $f) { ?>
                    <input type="hidden" id="pkfield_<?php echo $f; ?>" name="pkfield_<?php echo $f; ?>" value="<?php echo $f; ?>" />
                <?php } ?>
                <input type="hidden" id="oper" name="oper" value="get" />
                <input type="hidden" id="ajax" name="ajax" value="0" />
                <input type="hidden" id="mode" name="mode" value="new" />
                <div id="mant_head" class="ui-corner-all">
                    <div id="titulo"><?php echo $this->tittle; ?></div>
                    <div id="botones">
                        <button id="cmdDel" title="Eliminar Registro" type="button" onclick="javascript:setDelMode();">
                            <img alt="Eliminar Registro"  src="imgv2/actions/edit-delete.png" /></button>
                        <button id="cmdNew" title="Nuevo Registro" type="button" onclick="javascript:setNewMode();">
                            <img alt="Nuevo Registro"  src="imgv2/actions/document-new.png" /></button>
                        <button id="cmdOk" title="Guardar Registro" type="button"  onclick="javascript:sendFormData(true,this.form);">
                            <img alt="Guardar Registro"  src="imgv2/actions/document-save.png" />
                        </button>
                    </div>
                </div>
                <div id="tabs" >
                    <ul>
                        <li><a href="#tab1"><?php echo $this->tittle; ?></a></li>
                    </ul>
                    <div class="form-container" id="tab1" style="height: auto !important; font-size: 10px !important;">
                    <?php } ?>
                    <fieldset> <legend>Datos Registro</legend>
                        <?php
                        foreach ($this->fieldsConfig as $k => $v) {
                            $defValues = array();
                            $readOnly = false;
                            $defClass = "";
                            if (is_array($v)) {
                                $label = $v[0];
                                $type = $v[1];
                                if (is_array($type)) {
                                    $defValues = $type;
                                } else {
                                    $readOnly = ($type == "READONLY");
                                }
                                if (isset($v[2])) {
                                    $defClass = $v[2];
                                }
                            } else {
                                $label = $v;
                                $type = "text";
                            }
                            ?><div><label for="<?php echo $k; ?>"><?php echo $label; ?></label>
                                <?php if (count($defValues) > 0) {
                                    ?>
                                    <select class="<?php echo $defClass ?>"  name="<?php echo $k; ?>" id="<?php echo $k; ?>" 
                                            <?php echo $readOnly ? 'readonly="readonly"' : ''; ?>>
                                        <option value="">-</option>
                                        <?php
                                        foreach ($defValues as $val => $lab) {
                                            $t = "";
                                            if (isset($this->currentRecord[$k]) && $this->currentRecord[$k] == $val) {
                                                $t = 'selected="selected"';
                                            }
                                            ?>
                                            <option <?php echo $t; ?> value="<?php echo $val ?>"><?php echo $lab; ?> </option>
                                        <?php } ?>
                                    </select>
                                    <?php
                                } else {
                                    $val = isset($this->currentRecord[$k]) ? $this->currentRecord[$k] : "";
                                    if (isset($this->encryptedCols[$k])) {
                                        $val = "";
                                    }
                                    ?>
                                    <input class="<?php echo $defClass ?>" type="<?php echo $type; ?>" name="<?php echo $k; ?>" 
                                           value="<?php echo $val; ?>" id="<?php echo $k; ?>" 
                                           <?php echo $readOnly ? 'readonly="readonly"' : ''; ?>
                                           />
                                       <?php } ?>
                            </div>
                        <?php } ?>
                    </fieldset>
                    <?php
                    $this->includeWidget();
                    $this->currentRecord = array();
                    ?>
                    <?php if (!$ajax) {
                        ?>
                    </div>
                </div>
                <script type="text/javascript">
                    jQuery("#tabs").tabs();
                    setNewMode();
                </script>
            </form>
            <?php
        }
    }

    private function generaGrid() {
        $colNames = count($this->gridCols) > 0 ? $this->gridCols : array_keys($this->fieldsConfig);
        $colsLabel = array();
        $colModel = array();
        foreach ($colNames as $k) {
            $value = $this->fieldsConfig[$k];
            if (is_array($value)) {
                $value = $value[0];
            }
            $colsLabel[] = $value;
        }
        foreach ($colNames as $c) {
            $colModel[] = array("name" => $c, "index" => $c);
        }
        $this->cfgGrid = array(
            "url" => CORE_PATH . "?module=$this->instanceName&oper=gridop&" . AJAX_INDICATOR . "=true",
            "datatype" => "json",
            "height" => "100%",
            "autowidth" => true,
            "colNames" => $colsLabel,
            "colModel" => $colModel,
            "rowNum" => "20",
            "rowTotal" => "2000",
            "rowList" => explode(",", "50,80,120"),
            "mtype" => "POST",
            "gridview" => true,
            "pager" => "_pager_",
            "sortname" => $colNames[0],
            "viewrecords" => true,
            "sortorder" => "asc",
            "toolbar" => array(true, "top"),
            "caption" => "Listado Registros",
            "pkfields" => $this->pkFields
        );
        ?>

        <table style="font-size: 10px !important;" id="_grid_"></table>
        <div id="_pager_" ></div>
        <script type="text/javascript">
            var selectListener=function(){     
                var idVal = arguments[0];
                if ( opts ) {
                    var pks= opts.pkfields;
                    $.each(pks, function( ) {
                        $("#pkfield_" + this).val(idVal);
                    });
                }
                $("#ajax").val(1);
                $("#oper").val("get");
                var options = {         
                    target:'#tab1',
                    success:function(r){
                        $("html,body").animate({
                            scrollTop: $("#mant_head").offset().top-10
                        }, 1000);
                        $("#oper").val("upd");
                        jQuery("#_grid_").jqGrid().trigger("reloadGrid");
                        $.each(appCallbacks, function(fn){
                            if(fn && !isNumber(fn)){ 
                                fn(); 
                            }
                                           
                        });
                    }
                }    
                $(document.forms[0]).ajaxSubmit(options);           
            }
            var opts=<?php echo json_encode($this->cfgGrid); ?>;
            opts.onSelectRow=selectListener;
            $("#_grid_").jqGrid(opts);
            $("#_grid_").jqGrid('filterToolbar');
        </script>
        <?php
    }

    public function saveRec() {
        $colNames = array_keys($this->fieldsConfig);
        $data = array();
        foreach ($colNames as $p) {
            if ($p != $this->pkFields[0]) {
                $fld = $this->fieldsConfig[$p];
                if (is_array($fld) && $fld[1] == "READONLY") { //el indice 2 deberia traer el valor default
                    $val = $fld[2];
                    $data[$p] = sqlValue($val, "text");
                } else {
                    $val = getParam($p);
                    $val = $this->encryptField($p, $val);
                    $data[$p] = sqlValue($val, "text");
                }
            } else {
                $val = getParam($p);
                $val = $this->encryptField($p, $val);
                $data[$p] = sqlValue($val, "text");
            }
        }
        $this->db->query_insert($this->table, $data);
    }

    public function delRec() {
        $pk = sqlValue(getParam($this->pkFields[0]), "text");
        $this->db->query_delete($this->table, $this->pkFields[0] . "=$pk");
    }

    public function encryptField($fld, $val) {
        $encFld = array_values($this->encryptedCols);
        foreach ($encFld as $f) {
            if ($fld == $f) {
                return md5($val);
            }
        }
        return $val;
    }

    public function isPK($fld) {
        $keys = array_values($this->pkFields);
        foreach ($keys as $k) {
            if ($fld == $k) {
                return true;
            }
        }
        return false;
    }

    public function updateRec() {
        $colNames = array_keys($this->fieldsConfig);
        $data = array();
        foreach ($colNames as $p) {
            if (!$this->isPK($p) && !array_key_exists($p, $this->fieldsToSkipOnUpdate)) {
                $val = getParam($p);
                $val = $this->encryptField($p, $val);
                $data[$p] = sqlValue($val, "text");
            }
        }
        $where = "";
        $keys = array_values($this->pkFields);
        foreach ($keys as $pkcol) {
            $where = !isEmpty($where) ? "$where AND " : $where;
            $where .= "$pkcol=" . sqlValue(getParam($pkcol), "text");
        }
        print_r($data);
        $this->db->query_update($this->table, $data, $where);
    }

    private function getRecord() {
        $w = $this->getWhere();
        $r = $this->db->queryToArray("select * from $this->table $w ");
        $this->currentRecord = $r[0];
    }

    private function dispatchGridRequest() {
        if ($this->gridmanager == null) {
            //$colNames = array_keys($this->fieldsConfig);
            $colNames = $this->gridCols;
            $this->gridmanager = new JGridGenerator();
            $this->gridmanager->table = $this->table;
            $this->gridmanager->fields = $colNames;
            $this->gridmanager->pk = $this->pkFields[0];

            $a = array();
            foreach ($colNames as $c) {
                $a[$c] = "text";
            }
            $this->gridmanager->colTypes = $a;
        }
        $this->gridmanager->db = $this->db;
        $this->gridmanager->main();
    }

    private function getWhere() {
        $where = "";
        foreach ($this->pkFields as $pk) {
            $v = getParam("pkfield_$pk");
            $where = !isEmpty($where) ? "$where AND " : $where;
            $where.="$pk=" . sqlValue($v, "text");
        }
        return !isEmpty($where) ? "where $where" : "";
    }

    private function showPage() {
        ?>
        <div id="maintenancecontainer" style="height: auto;">
            <div id="formpanel">
                <?php
                $this->generaForma();
                ?></div>
            <div id="gridpanel">
                <?php $this->generaGrid(); ?>
            </div>
        </div>
        <?php
    }

    public function main() {
        if (!isEmpty(getParam("oper"))) {
            switch (getParam("oper")) {
                case "add": {
                        $this->saveRec();
                        break;
                    }
                case "upd": {
                        getParam("oper");
                        $this->updateRec();
                        break;
                    }
                case "del": {
                        $this->delRec();
                        break;
                    }
                case "get": {
                        $this->getRecord();
                        $this->generaForma(true);
                        break;
                    }
                case "gridop": {
                        $this->dispatchGridRequest();
                        break;
                    }
            }
        } else {
            $this->showPage();
        }
    }

}
?>
